﻿using SuperX.Common;
using SuperX.Common.APIManager;
using SuperX.Common.BasicService;
using SuperX.Common.Log;
using SuperX.DataService;
using SuperX.Helper;
using SuperX.Helper.PageBreak;
using SuperX.Helper.ServiceResponse;
using SuperX.DeviceService.Model;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;

namespace SuperX.DeviceService.Template
{
    public class DeviceTemplateController : DynamicApiController
    {
        private readonly DeviceServer _server;
        private IProject _project = BasicServiceManager.GetProjService().Project;

        public DeviceTemplateController(DeviceServer server)
        {
            _server = server;
            Name = nameof(DeviceTemplateController);
        }

        [WebApi("创建模板", "", "")]
        public ApiResponse<bool> CreateTemplate(string driverFullName)
        {
            if (string.IsNullOrEmpty(driverFullName))
                return ApiResponse<bool>.Fail("参数不合法！");

            var driver = _project.Objects[driverFullName] as DriverConfig;
            if (driver == null)
                return ApiResponse<bool>.Fail("配置文件中，未找到该驱动！");

            if (_server.TemplateManager.CreateTemplate(driver, out string msg))
                return ApiResponse<bool>.Success("模板添加成功！", true);
            return ApiResponse<bool>.Success($"模板添加失败，{msg}！");
        }

        [WebApi("获取模板集合", "", "")]
        public ApiResponse<List<TemplateDriverConfig>> GetTemplateCollection()
        {
            return _server.TemplateManager.GetTemplateCollection(_server.DataManager.GetDefaultDriverConfig()).ToResponse();
        }

        [WebApi("从模板新增设备", "", "")]
        public ApiResponse<bool> AddDriverByTemplate(string templateName, int quantity, string NodeKey, bool isSync)
        {
            if (string.IsNullOrEmpty(templateName) || quantity < 0)
                return ApiResponse<bool>.Fail("参数不合法！");

            var templateDriver = _project.Objects[templateName] as DriverConfig;
            if (templateDriver == null)
                return ApiResponse<bool>.Fail("配置文件中，未找到该驱动的模板！");

            var tip = _server.TemplateManager.AddDriverByTemplate(quantity, templateDriver, NodeKey, isSync);
            if (tip == "")
                return ApiResponse<bool>.Success("添加成功！", true);
            return ApiResponse<bool>.Fail(tip);
        }

        [WebApi("获取模板树", "", "")]
        public ApiResponse<List<TreeModel>> GetTemplateTree(string templateFullName)
        {
            var driverTree = new List<TreeModel>();
            try
            {
                if (string.IsNullOrEmpty(templateFullName))
                    return ApiResponse<List<TreeModel>>.Fail("参数不合法！");

                if (!_project.Objects.ContainsKey(templateFullName))
                    return ApiResponse<List<TreeModel>>.Fail("配置文件中，未找到该驱动的模板！");
                var templateDriver = _project.Objects[templateFullName] as DriverConfig;
                if (templateDriver == null)
                    return ApiResponse<List<TreeModel>>.Fail("配置文件中，未找到该驱动的模板！");

                TreeModel treeModel = new TreeModel();
                treeModel.Key = templateDriver.FullName;
                treeModel.Type = 1;
                treeModel.Parentkey = "Server";
                treeModel.Name = templateDriver.Name;
                foreach (var item in templateDriver.Groups)
                {
                    treeModel.Children.Add(new TreeModel()
                    {
                        Parentkey = templateDriver.FullName,
                        Key = item.FullName,
                        Name = item.Name,
                        Type = 2,
                        SystemType = item.GroupType,
                    });
                }
                driverTree.Add(treeModel);
            }
            catch (System.Exception ex)
            {
                Logger.ErrorException(ex);
            }
            var data = new List<TreeModel>() { new TreeModel() { Parentkey = null, Key = "Server", Type = 0, Name = "模板", Children = driverTree } };
            return data.ToResponse();
        }

        [WebApi("查询模板信息", "驱动Name", "驱动对象")]
        public ApiResponse<DriverConfig> GetTemplat(string templateFullName)
        {
            var Driver = _project.Objects[templateFullName] as DriverConfig;
            if (Driver == null) return ApiResponse<DriverConfig>.Fail("查询失败，未找到此模板！");
            JObject config = JObject.FromObject(Driver);
            config.Remove("GroupConfigs");
            return ApiResponse<DriverConfig>.Success(data: Driver);
        }

        [WebApi("删除模板", "", "")]
        public ApiResponse<bool> DelTemplate(string templateFullName, bool delDevice)
        {
            if (string.IsNullOrEmpty(templateFullName))
                return ApiResponse<bool>.Fail("参数不合法！");

            var Template = _project.Objects[templateFullName] as DriverConfig;
            if (Template == null) return ApiResponse<bool>.Fail("删除失败，未找到此模板！");
            _server.TemplateManager.TConfig.TemplateItem.Remove(Template);
            if (delDevice)
            {
                var drivers = _server.DataManager.Config.DriverGroups.Values.Where(d => d.TemplateId == Template.TemplateId).ToList();
                foreach (var driver in drivers)
                {
                    _server.DataManager.Config.DriverGroups.Remove(driver);
                }
            }

            return ApiResponse<bool>.Success("删除成功！");
        }

        [WebApi("修改模板", "", "")]
        public ApiResponse<string> UpdateTemplate(string templateFullName, DriverConfig driver)
        {
            Helper.Validation.ValidationMain.ScanIsValid(driver);
            var Driver = _project.Objects[templateFullName] as DriverConfig;
            if (Driver == null) return ApiResponse<string>.Fail("更新失败，未找到此模板驱动！");
            ConfigReflectionHelper.AutoMapping(Driver, driver, skip: "Groups,Item,FullName");
            return ApiResponse<string>.Success(data: Driver.FullName);
        }

        [WebApi("新增模板分组信息", "驱动Name,驱动对象", "返回bool")]
        public ApiResponse<string> AddTemplateGroup(string templateFullName, GroupConfig groupConfig)
        {
            var Driver = _project.Objects[templateFullName] as DriverConfig;
            if (Driver == null) return ApiResponse<string>.Fail("添加失败，未找到此模板驱动！");
            Helper.Validation.ValidationMain.ScanIsValid(groupConfig);
            Driver.Groups.Add(groupConfig);
            return ApiResponse<string>.Success();
        }

        [WebApi("删除模板分组信息", "驱动Name,分组Name", "返回bool")]
        public ApiResponse<object> DelTemplateGroup(string templateFullName, string templateGroupName)
        {
            var Driver = _project.Objects[templateFullName] as DriverConfig;
            var Group = _project.Objects[templateGroupName] as GroupConfig;
            if (Driver == null || Group == null) return ApiResponse<object>.Fail("删除失败，未找到此模板驱动或者分组！");
            var isDel = Driver.Groups.Remove(Group);
            return ApiResponse<object>.Success(data: isDel);
        }

        [WebApi("更新模板分组信息", "驱动Name,分组Name,分组对象", "返回bool")]
        public ApiResponse<string> UpdateTemplateGroup(string templateFullName, string templateGroupName, GroupConfig groupConfig)
        {
            Helper.Validation.ValidationMain.ScanIsValid(groupConfig);
            var Driver = _project.Objects[templateFullName] as DriverConfig;
            var Group = _project.Objects[templateGroupName] as GroupConfig;
            if (Driver == null || Group == null) return ApiResponse<string>.Fail("更新失败，未找到此模板驱动或者分组！");
            ConfigReflectionHelper.AutoMapping(Group, groupConfig, skip: "TagGroups,Item,FullName");
            return ApiResponse<string>.Success();
        }

        [WebApi("查询模板分组信息", "驱动Name,分组Name", "返回bool")]
        public ApiResponse<JObject> GetTemplateGroup(string templateFullName, string templateGroupName)
        {
            var Driver = _project.Objects[templateFullName] as DriverConfig;
            var Group = _project.Objects[templateGroupName] as GroupConfig;
            if (Driver == null || Group == null) return ApiResponse<JObject>.Fail("查询失败，未找到此驱动或者分组！");
            JObject config = JObject.FromObject(Group);
            config.Remove("TagMetaDatas");
            return ApiResponse<JObject>.Success(data: config);
        }

        [WebApi("新增模板Tag", "设备Name,组Name", "返回bool")]
        public ApiResponse<string> AddTemplateTag(string templateFullName, string templateGroupName, TagConfig tag)
        {
            Helper.Validation.ValidationMain.ScanIsValid(tag);
            var Driver = _project.Objects[templateFullName] as DriverConfig;
            var Group = _project.Objects[templateGroupName] as GroupConfig;
            if (Driver == null || Group == null) return ApiResponse<string>.Fail("新增失败，未找到此模板驱动或者分组！");
            var driverBase = _server.DataManager.GetDriver(Driver.AssemblyName, Driver.ClassFullName, Driver.Argument);
            tag.Address = driverBase.AddressCombin(tag.Regester, tag.No);
            if (tag.TagType == TagType.Normal)
            {
                var checkResult = driverBase.CheckAddressLegal(tag.Address, tag.DataType);
                if (!checkResult) return ApiResponse<string>.Fail("新增失败，寄存器地址校验不通过！");
            }
            Group.TagGroups.Add(tag);
            return ApiResponse<string>.Success();
        }

        [WebApi("删除模板Tag", "设备Name,组Name,Tag的Name", "返回true或false")]
        public ApiResponse<string> DelTemplateTag(string templateFullName, string templateGroupName, string tagName)
        {
            var Driver = _project.Objects[templateFullName] as DriverConfig;
            var Group = _project.Objects[templateGroupName] as GroupConfig;
            var tag = Group.TagGroups[tagName];
            if (Driver == null || Group == null || tag == null)
                return ApiResponse<string>.Fail("删除失败，未找到此模板驱动或者分组！");
            Group.TagGroups.Remove(tag);
            return ApiResponse<string>.Success();
        }

        [WebApi("修改模板Tag", "设备Name,组Name,TagName,tag对象", "")]
        public ApiResponse<string> UpdateTemplateTag(string templateFullName, string templateGroupName, string TagName, TagConfig tag)
        {
            var driver = _project.Objects[templateFullName] as DriverConfig;
            var group = _project.Objects[templateGroupName] as GroupConfig;
            var deltag = group.TagGroups[TagName];
            if (driver == null || group == null || deltag == null) return ApiResponse<string>.Fail("修改失败！");
            var driverBase = _server.DataManager.GetDriver(driver.AssemblyName, driver.ClassFullName, driver.Argument);
            tag.Address = driverBase.AddressCombin(tag.Regester, tag.No);
            ConfigReflectionHelper.AutoMapping(deltag, tag, skip: "Item,FullName");
            return ApiResponse<string>.Success();
        }

        [WebApi("获取模板Tags", "", "")]
        public ApiResponse<PageResult<TagConfig>> GetTemplateTag(TagQueryInputDto input)
        {
            if (input == null || string.IsNullOrEmpty(input.GroupKey) || string.IsNullOrEmpty(input.DriverKey))
                return ApiResponse<PageResult<TagConfig>>.Fail("参数不合法！");
            if (input.DriverKey == "-1" || input.GroupKey == "-1")
                return ApiResponse<PageResult<TagConfig>>.Success(data: new PageResult<TagConfig>());//前端要求
            return ApiResponse<PageResult<TagConfig>>.Success(data: _server.TemplateManager.GetTagInfo(input));
        }

        [WebApi("保存模板并更新设备", "", "")]
        public ApiResponse<bool> SaveTemplateandUpdate(string templateFullName)
        {
            if (string.IsNullOrEmpty(templateFullName))
                return ApiResponse<bool>.Fail("参数不合法！");
            if (_server.TemplateManager.SaveTemplateandUpdate(templateFullName, out string msg))
                return ApiResponse<bool>.Success(msg, true);
            return ApiResponse<bool>.Fail("模板保存成功！设备更新失败！");
        }
    }
}